package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long id) {
        // 1.根据分类id查询规格组的集合
        List<SpecGroup> specGroupList = query().eq("category_id", id).list();
        if(CollectionUtils.isEmpty(specGroupList)){
            // 不存在，返回空集合
            return Collections.emptyList();
        }
        // 2.组织groupDTO集合
        List<SpecGroupDTO> dtoList = SpecGroupDTO.convertEntityList(specGroupList);

        // 3.根据分类id查询规格参数集合
        List<SpecParamDTO> params = paramService.querySpecParams(id, null, null);

        // 4.把params依据groupId分组，groupId一致的放到一个组，存入集合:
        // Map<Long, List<SpecParam>> key是groupId，值是groupId一致的param集合
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 5.组装，根据groupId去map找
        for (SpecGroupDTO specGroup : dtoList) {
            List<SpecParamDTO> paramDTOS = map.get(specGroup.getId());
            specGroup.setParams(paramDTOS);
        }

        return dtoList;
    }
}